package com.tonann.app.service.impl;

import com.tonann.app.domain.AppSensorRecord;
import com.tonann.app.domain.AppSensorRecordDay;
import com.tonann.app.domain.AppSensorRecordHour;
import com.tonann.app.domain.AppSensorRecordMonth;
import com.tonann.app.mapper.AppSensorRecordDayMapper;
import com.tonann.app.mapper.AppSensorRecordHourMapper;
import com.tonann.app.mapper.AppSensorRecordMapper;
import com.tonann.app.mapper.AppSensorRecordMonthMapper;
import com.tonann.app.service.IAppSensorRecordService;
import com.tonann.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 运行记录Service业务层处理
 *
 * @author tonann
 * @date 2022-10-21
 */
@Service
public class AppSensorRecordServiceImpl implements IAppSensorRecordService {

    @Resource
    private  AppSensorRecordMapper appSensorRecordMapper;
    @Resource
    private AppSensorRecordHourMapper sensorRecordHoursMapper;
    @Resource
    private AppSensorRecordDayMapper sensorRecordDayMapper;
    @Resource
    private AppSensorRecordMonthMapper sensorRecordMonthMapper;

    /**
     * 查询运行记录
     *
     * @param recordId 运行记录主键
     * @return 运行记录
     */
    @Override
    public AppSensorRecord selectAppSensorRecordByRecordId(Long recordId) {
        return appSensorRecordMapper.selectAppSensorRecordByRecordId(recordId);
    }

    /**
     * 查询运行记录列表
     *
     * @param appSensorRecord 运行记录
     * @return 运行记录
     */
    @Override
    public List<AppSensorRecord> selectAppSensorRecordList(AppSensorRecord appSensorRecord) {
//        if (appSensorRecord.getSensorId() != null){
//            LocalDateTime localDateTime = LocalDateTime.now();
//            LocalDateTime localDateTimeHours =  localDateTime.minusHours(12);
//            String timeHours =localDateTimeHours.getYear() + "-"+completionZero(localDateTimeHours.getMonthValue())
//                    + "-" + completionZero(localDateTimeHours.getDayOfMonth())
//                    +" " + completionZero(localDateTimeHours.getHour()) + ":00:00";
//            localDateTimeHours = LocalDateTime.parse(timeHours,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//            AppSensorRecordHour recordHour = new AppSensorRecordHour();
//            recordHour.setSensorId(appSensorRecord.getSensorId());
//            recordHour.setCreateTime(localDateTimeHours);
//            List<AppSensorRecordHour> hoursList = sensorRecordHoursMapper.selectAppSensorRecordHourList(recordHour);
//            System.out.println(hoursList);
//            LocalDate localDateTimeDay = LocalDate.from(localDateTime.minusHours(24));
//            AppSensorRecordDay sensorRecordDay = new AppSensorRecordDay();
//            sensorRecordDay.setSensorId(appSensorRecord.getSensorId());
//            sensorRecordDay.setCreateTime(localDateTimeDay);
//            List<AppSensorRecordDay> dayList = sensorRecordDayMapper.selectAppSensorRecordDayList(sensorRecordDay);
//            System.out.println(dayList);
//            LocalDate localDateMonth = LocalDate.parse("2024-11-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//            AppSensorRecordMonth sensorRecordMonth = new AppSensorRecordMonth();
//            sensorRecordMonth.setSensorId(appSensorRecord.getSensorId());
//            sensorRecordMonth.setCreateTime(localDateMonth);
//            List<AppSensorRecordMonth> monthList = sensorRecordMonthMapper.selectAppSensorRecordMonthList(sensorRecordMonth);
//            System.out.println(monthList);
//            List<AppSensorRecord> appSensorRecordList = appSensorRecordMapper.selectAppSensorRecordList(appSensorRecord);
//            Map<LocalDateTime, List<AppSensorRecord>> dateMap = appSensorRecordList.stream().collect(Collectors.groupingBy(event -> event.getCreateTime().toLocalDate().atStartOfDay().plusHours(event.getCreateTime().getHour())));
//            List<AppSensorRecordHour> recordHoursList = new ArrayList<>();
//            for (LocalDateTime dateTime : dateMap.keySet()) {
//                AppSensorRecordHour hours = new AppSensorRecordHour();
//                AppSensorRecord record = dateMap.get(dateTime).get(0);
//                hours.setSensorId(record.getSensorId());
//                hours.setCreateTime(dateTime);
//                List<AppSensorRecordHour> recordHours = sensorRecordHoursMapper.selectAppSensorRecordHourList(hours);
//                if (recordHours == null || recordHours.isEmpty()) {
//                    Optional<BigDecimal> maxOptional = dateMap.get(dateTime).stream().map(AppSensorRecord::getValue).map(BigDecimal::new).max(BigDecimal::compareTo);
//                    if (maxOptional.isPresent()) {
//                        BigDecimal max = maxOptional.get();
//                        hours.setValue(max.toString());
//                        sensorRecordHoursMapper.insertAppSensorRecordHour(hours);
//                        LocalDateTime creatTime = record.getCreateTime();
//                        LocalDateTime now = LocalDateTime.now();
//                        long daysDiff = ChronoUnit.DAYS.between(creatTime, now);
//                        if (daysDiff >= 30) {
////                            appSensorRecordMapper.deleteAppSensorRecordByRecordId(record.getRecordId());
//                        }
//                        recordHoursList.add(hours);
//                    }
//                }
//            }
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            Map<String, List<AppSensorRecordHour>> dayMap = recordHoursList.stream().collect(Collectors.groupingBy(ldt -> ldt.getCreateTime().format(formatter)));
//            List<AppSensorRecordDay> recordDayList = new ArrayList<>();
//            for (String day : dayMap.keySet()) {
//                AppSensorRecordDay recordDay = new AppSensorRecordDay();
//                AppSensorRecordHour record = dayMap.get(day).get(0);
//                recordDay.setSensorId(record.getSensorId());
//                LocalDate localDateDay = LocalDate.parse(day,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//                recordDay.setCreateTime(localDateDay);
//                List<AppSensorRecordDay> sensorRecordDays = sensorRecordDayMapper.selectAppSensorRecordDayList(recordDay);
//                if (sensorRecordDays == null || sensorRecordDays.isEmpty()) {
//                    Optional<BigDecimal> maxOptional = dayMap.get(day).stream().map(AppSensorRecordHour::getValue).filter(Objects::nonNull).map(BigDecimal::new).max(BigDecimal::compareTo);
//                    if (maxOptional.isPresent()) {
//                        BigDecimal max = maxOptional.get();
//                        recordDay.setValue(max.toString());
//                        sensorRecordDayMapper.insertAppSensorRecordDay(recordDay);
//                        recordDayList.add(recordDay);
//                    }
//                }
//            }
//            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM");
//            Map<String, List<AppSensorRecordDay>> monthMap = recordDayList.stream().collect(Collectors.groupingBy(ldt -> ldt.getCreateTime().format(formatter1)));
//            for (String day : monthMap.keySet()) {
//                AppSensorRecordMonth recordMonth = new AppSensorRecordMonth();
//                AppSensorRecordDay record = monthMap.get(day).get(0);
//                recordMonth.setSensorId(record.getSensorId());
//                LocalDate localDate = LocalDate.parse(day+"-01");
//                recordMonth.setCreateTime(localDate);
//                List<AppSensorRecordMonth> recordMonths = sensorRecordMonthMapper.selectAppSensorRecordMonthList(recordMonth);
//                if (recordMonths == null || recordMonths.isEmpty()) {
//                    Optional<BigDecimal> maxOptional = monthMap.get(day).stream().map(AppSensorRecordDay::getValue).map(BigDecimal::new).max(BigDecimal::compareTo);
//                    if (maxOptional.isPresent()) {
//                        BigDecimal max = maxOptional.get();
//                        recordMonth.setValue(max.toString());
//                        sensorRecordMonthMapper.insertAppSensorRecordMonth(recordMonth);
//                    }
//                }
//            }
//        }
        return appSensorRecordMapper.selectAppSensorRecordList(appSensorRecord);
    }

    private String completionZero(Integer num){
        if (num < 10){
            return  "0"+num;
        }else {
            return num.toString();
        }
    }
    /**
     * 新增运行记录
     *
     * @param appSensorRecord 运行记录
     * @return 结果
     */
    @Override
    public int insertAppSensorRecord(AppSensorRecord appSensorRecord) {
        appSensorRecord.setCreateTime(LocalDateTime.now());
        Date date = new Date();
        appSensorRecord.setSaveTime(date.getTime());
        return appSensorRecordMapper.insertAppSensorRecord(appSensorRecord);
    }

    /**
     * 修改运行记录
     *
     * @param appSensorRecord 运行记录
     * @return 结果
     */
    @Override
    public int updateAppSensorRecord(AppSensorRecord appSensorRecord) {
        appSensorRecord.setUpdateTime(LocalDateTime.now());
        return appSensorRecordMapper.updateAppSensorRecord(appSensorRecord);
    }

    /**
     * 批量删除运行记录
     *
     * @param recordIds 需要删除的运行记录主键
     * @return 结果
     */
    @Override
    public int deleteAppSensorRecordByRecordIds(Long[] recordIds) {
        return appSensorRecordMapper.deleteAppSensorRecordByRecordIds(recordIds);
    }

    /**
     * 删除运行记录信息
     *
     * @param recordId 运行记录主键
     * @return 结果
     */
    @Override
    public int deleteAppSensorRecordByRecordId(Long recordId) {
        return appSensorRecordMapper.deleteAppSensorRecordByRecordId(recordId);
    }

    @Override
    public List<AppSensorRecord> selectAppSensorRecordPureList(AppSensorRecord appSensorRecord) {
        return appSensorRecordMapper.selectAppSensorRecordPureList(appSensorRecord);
    }

    @Override
    public AppSensorRecord selectAppSensorRecordBySensorId(Long sensorId) {
        return appSensorRecordMapper.selectAppSensorRecordBySensorId(sensorId);
    }

    @Override
    public AppSensorRecord selectPreNoZeroAppSensorRecordByRecordId(Long recordId,Long sensorId) {
        return appSensorRecordMapper.selectPreNoZeroAppSensorRecordByRecordId(recordId,sensorId);
    }

    @Override
    public AppSensorRecord selectPreNoZeroAppSensorRecordByTime(LocalDateTime createTime, Long sensorId) {
        return  appSensorRecordMapper.selectPreNoZeroAppSensorRecordByTime(createTime, sensorId);
    }

    @Override
    public void deleteAppSensorRecordBefore30Day() {
        appSensorRecordMapper.deleteAppSensorRecordBefore30Day();
    }
}
